package by.cooker.chat.logic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author cooker
 */
public class Receiver implements Runnable
{

	private LinkedBlockingQueue<String> messages;

	private BufferedReader reader;

	/**
	 * Receiver constructor.
	 * 
	 * @param socket
	 *            - socket.
	 * @param message
	 *            - messages queue.
	 * @throws IOException
	 *             - if I/O problem.
	 */
	public Receiver(LinkedBlockingQueue<String> messages) throws IOException
	{
		this.messages = messages;
		reader = new BufferedReader(new InputStreamReader(Client.getClient()
				.getSocket().getInputStream()));

		// skip 155 characters this is a error messages from server about
		// incorrect logon ...
		reader.skip(155);
	}

	/**
	 * Read message from server.
	 * 
	 * @return message.
	 */
	public String readMsg()
	{
		String msg = null;
		try
		{
			msg = reader.readLine();
		} catch (IOException ex)
		{
			ex.printStackTrace();
		}
		return msg;
	}

	public void run()
	{
		String str = null;
		boolean done = false;
		while (!done)
		{
			try
			{
				if ((str = readMsg()) != null)
				{
					messages.put(str);
				}
			} catch (InterruptedException ex)
			{
				ex.printStackTrace();
			}
		}
	}

}
